/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.socket.server.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;

import com.bambamboo.socket.server.AbstractIOServer;
import com.bambamboo.socket.server.ServerConfigurationBean;

/**
 * DOCME
 * 
 * @author Nick.Tan
 */
public class NettyUDPServer extends AbstractIOServer {

	private static Log logger = LogFactory.getLog(NettyUDPServer.class);

	@Override
	public void startup() throws Exception {
		ChannelFactory factory = new NioDatagramChannelFactory(Executors.newCachedThreadPool());

		ServerBootstrap bootstrap = new ServerBootstrap(factory);
		ChannelPipeline pipeline = bootstrap.getPipeline();
		ServerConfigurationBean bean = getServerConfigurationBean();
		SimpleChannelUpstreamHandler channelHandler = new EchoHandler();

		pipeline.addLast("handler", channelHandler);
		String port = bean.getPort();
		try {
			bootstrap.bind(new InetSocketAddress(Integer.parseInt(port)));
			logger.info(String.format(">>> listening on port [%s]", port));
		}
		catch (Exception e) {
			// catch to continue binding other ports
			logger.error(String.format(">>> binding on port [%s] failure!", port), e);
		}
	}

}
